package com.zhuqi.config;

import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : ZhuQi
 * @version : 时间:2022/3/22 9:45 版本:
 */
@Configuration
@Log4j2
public class SpringSecurityConfiguration {

    @Bean
    public  UserDetailsService myUserDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        String[][] userGroupsAnRoles ={
                {"jack","password","ROLE_ACTIVITI_USER","GROUP_activititeam"},
                {"rose","password","ROLE_ACTIVITI_USER","GROUP_activititeam"},
                {"admin","password","ROLE_ACTIVITI_ADMIN"}
        };

        for (String[] userGroupsAnRole : userGroupsAnRoles) {
            List<String> authList = Arrays.asList(Arrays.copyOfRange(userGroupsAnRole, 2, userGroupsAnRole.length));
            inMemoryUserDetailsManager.createUser(new User(userGroupsAnRole[0]
                    , passwordEncoder().encode(userGroupsAnRole[1])
                    , authList.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())
            ));
        }

        return inMemoryUserDetailsManager;
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
